package com.hedd.shop.service.impl;

import com.hedd.shop.mapper.CartMapper;
import com.hedd.shop.pojo.entity.Cart;
import com.hedd.shop.pojo.qo.CartAddQO;
import com.hedd.shop.pojo.qo.CartUpdateQO;
import com.hedd.shop.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author ludi
 * @date:2020/8/31 0:17
 * @description:购物车业务
 */
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private CartMapper cartMapper;

    @Transactional(readOnly = true)
    @Override
    public int addCart(CartAddQO cartAddQO) {
        System.out.println("addCart begin");
        //添加购物车，判断添加的购物车商品id是否重复，重复则数量加1，否则添加新的一条购物车
        List<Cart> list = cartMapper.selectByUserId(cartAddQO.getUserId());
        for (Cart cart : list) {
            if(cart.getProduct().getProductId()==cartAddQO.getProductId()){
                cart.getProduct().getPrice();
                cart.setNum(cart.getNum()+1);
                return cartMapper.updateCart(new CartUpdateQO(cart.getNum(), cart.getCartId(), cart.getTotalPrice()));
            }
        }
        return cartMapper.addCart(cartAddQO);
    }

    @Override
    public List<Cart> selectByUserId(Integer userId) {
        return cartMapper.selectByUserId(userId);
    }

    @Transactional(readOnly = true)
    @Override
    public int updateCart(CartUpdateQO cartUpdateQO) {
        Cart cart = cartMapper.selectByCartId(cartUpdateQO.getCartId());
        cart.setNum(cartUpdateQO.getNum());
        cartUpdateQO.setTotalPrice(cart.getTotalPrice());
        return cartMapper.updateCart(cartUpdateQO);
    }

    @Override
    public Cart selectByCartId(Integer cartId) {
        return cartMapper.selectByCartId(cartId);
    }

    @Override
    public int deleteByCartId(Integer cartId) {
        return cartMapper.deleteByCartId(cartId);
    }

    @Override
    public int deleteAllByUserId(Integer userId) {
        return cartMapper.deleteAllByUserId(userId);
    }
}
